package test;

public class demo2 {
    //阻塞队列
    int[] arr = new int[10];
    int head = 0;
    int tail = 0;
    int size = 0;

    public void put(int i) throws InterruptedException {
        synchronized (this){
            while(size == arr.length){
                this.wait();
            }
            arr[tail++] = i;
            if(tail == arr.length){
                tail = 0;
            }
            size++;
            this.notify();
        }
    }
    public int take() throws InterruptedException {
        int num;
        synchronized (this){
            while(size == 0){
                this.wait();
            }
            num = arr[head++];
            if(head == arr.length){
                head = 0;
            }
            size--;
            this.notify();
        }
        return num;
    }

    public static void main(String[] args) {
        demo2 demo2 = new demo2();
        //生产者生产
        Thread t1 = new Thread(()-> {
            int num = 0;
            while(true){
                try {
                    num++;
                    demo2.put(num);
                    System.out.println("生产者生产" + num);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t2 = new Thread(()-> {
            while(true){
                try {
                    Thread.sleep(500);
                    int ret = demo2.take();
                    System.out.println("消费者消费" + ret);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
